﻿using System;
using System.Net;
using System.Reactive.Concurrency;

namespace nRoute.Components.Composition
{
    public class SingletonLifetimeManager
        : ILifetimeManager
    {
        private readonly object _lock = new Object();
        private Object _instance;

        public SingletonLifetimeManager() { }

#region ILifetimeManager Related

        public Object ManageBuild(ITypeBuilder typeBuilder, Func<ITypeBuilder, Object> resourceBuilder)
        {
            // not sync on read?
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = resourceBuilder(typeBuilder);
                    }
                }
            }

            return _instance;
        }

        protected virtual void Dispose(bool disposing) 
        {
            if (disposing)
            {
                if (_instance != null)
                {
                    lock (_lock)
                    {
                        _instance = null;
                    }
                }
            }
        }

#endregion

#region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

#endregion

        ~SingletonLifetimeManager() { Dispose(false); }

    }
}
